//
//  CIImageViewController.swift
//  CPT3
//
//  Created by onemade on 12/8/15.
//  Copyright © 2015 CNPC. All rights reserved.
//

import UIKit

class CIImageViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var label: UILabel!
    var flag = 0
    var image: UIImage!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        image = UIImage(named: "BW.jpg")
        imageView.image = image!
        label.text = ""
    }
    
    @IBAction func changeValue(sender: UISlider) {
        let value = sender.value
        switch flag {
        case 0:
            filterSepiaTone(value)
        case 1:
            filterGaussianBlur(value)
        default: break
        }
    }
    @IBAction func segmentSelected(sender: UISegmentedControl) {
        if sender.selectedSegmentIndex == 0{
            flag = 0
        }else{
            flag = 1
        }
    }
    func filterSepiaTone(value: Float){
        let context = CIContext()
        let ciImage = CIImage(CGImage: self.image.CGImage!)
        let sepiaTone = CIFilter(name: "CISepiaTone")
        sepiaTone?.setValue(ciImage, forKey: "inputImage")
        let text = String(format: "旧色调 Intensity: %.2f", value)
        label.text = text
        
        sepiaTone?.setValue(value, forKey: "inputIntensity")
        let result = sepiaTone?.valueForKey("outputImage") as! CIImage
        let imageRef = context.createCGImage(result, fromRect: CGRectMake(0, 0, imageView.image!.size.width, imageView.image!.size.height))
        let image = UIImage(CGImage: imageRef)
        imageView.image = image
        flag = 0
    }
    func filterGaussianBlur(value: Float) {
        let context = CIContext()
        let cImage = CIImage(CGImage: self.image.CGImage!)
        let gaussianBlur = CIFilter(name: "CIGaussianBlur")
        gaussianBlur?.setValue(cImage, forKey: "inputImage")
        let text = String(format: "高斯模糊 Radius: %.2f", value)
        label.text = text
        gaussianBlur?.setValue(value, forKey: "inputRadius")
        let result = gaussianBlur?.valueForKey("outputImage") as! CIImage
        let imageRef = context.createCGImage(result, fromRect: CGRectMake(0, 0, imageView.image!.size.width, imageView.image!.size.height))
        let image = UIImage(CGImage: imageRef)
        imageView.image = image
        flag = 1
    }
}
